//
//  HMMainTabBar.swift
//  WeiBoPractise
//
//  Created by 邹花平 on 16/4/10.
//  Copyright © 2016年 邹花平. All rights reserved.
//

import UIKit

class HMMainTabBar: UITabBar
    
{
    //1.定义闭包属性,传递
    var composeClosure:(() -> ())?
    
    //重写layoutsubView方法
    override func layoutSubviews()
        {
            super.layoutSubviews()//重写父类方法后一定记得调用一下父类
            
            let buttonCount = 5
            
            //宽度
            let width = self.frame.size.width / CGFloat(buttonCount)//记得给buttonCount指定一下数据类型
            //创建frame
            let newFrame = CGRect(x: 0, y: 0, width: width, height: frame.size.height)
            
            var index = 0
            
            for subView in subviews
            {
                if subView.isKindOfClass(NSClassFromString("UITabBarButton")!)
                {
                    //frame 可以平移 , 使用CGRectOffset
                    subView.frame = CGRectOffset(newFrame, CGFloat(index) * width, 0)
                    
                    index += index == 1 ? 2:1//注意?前面一定要有个空格
                
                
                }
            
            }
            
            //计算 x: 2 * width 排在第三,所以x的坐标就为前面两个按钮的长度
              composeButton.frame = CGRect(x: 2 * width, y: 0, width: width, height: frame.size.height)
        
        }
    
     //MARK: - 添加点击事件
    // @objc: 让OC可以调用我们swift的方法,系统默认会为所有的swift方法加上@objc,如果方法加了private,就不会帮我们加@objc
   @objc private func didClickComposeButton()
    {
        //调用闭包
        composeClosure?()
        
//        print("加号按钮被点击了")
    
    }

    
    //MARK: - 懒加载
    //加号按钮 尾随闭包
    private lazy var composeButton: UIButton =
    {
        let button = UIButton()
        
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        //给按钮添加一张图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.addTarget(self, action: Selector("didClickComposeButton"), forControlEvents:UIControlEvents.TouchUpInside)
        
        //添加按钮到tabbar
        
        self.addSubview(button)//为什么直接输入self , 接着点不出addSubview来呢?
        
      return button
    }()
    
    

    

    

}
